package com.loiot.commons.zookeeper;

import java.io.IOException;

import lombok.Setter;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import com.loiot.commons.zookeeper.lock.WriteLock;

/**
 * 锁服务类，提供zookeeper的服务
 * 
 * @author yanjg
 */
public class WagangLockService {

    private ZooKeeper keeper;

    /**
     * zookeeper地址
     */
    @Setter
    private String zookeeperUrl;
    /**
     * zookeeper端口
     */
    @Setter
    private int sessionTimeout;
    /**
     * lock目录
     */
    @Setter
    private String lockDir;

    /**
     * 初始化自动添加节点链
     * 
     * @throws IOException
     */
    public void init() throws IOException {
        keeper = new ZooKeeper(zookeeperUrl, sessionTimeout, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                System.out.println("已经触发了" + event.getType() + "事件！");
            }
        });
    }

    /**
     * 获得一个锁
     * 
     * @param dir 锁定目录
     * @return 锁
     */
    public WriteLock getLock() {
        WriteLock leader = new WriteLock(keeper, lockDir, null);
        return leader;
    }
}
